package com.jiguang.property.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.jiguang.property.service.OssFileService;
import com.jiguang.property.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssFileServiceImpl implements OssFileService {
    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        //通过工具类utiles取值
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        //创建OSS实例
        OSS ossClent = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //获取上传文件流
        InputStream inputStream = file.getInputStream();
        //获取文件名称
        String fileName = file.getOriginalFilename();
        //在文件名称里添加随机唯一的值
        String uuid = UUID.randomUUID().toString().replaceAll("-", " ");
        fileName = uuid + fileName;
        //把文件按日期进行分类
        String dataPath = new DateTime().toString("yyyy/MM/dd");
        fileName = dataPath + "/" + fileName;

        //上传图片
        ossClent.putObject(bucketName, fileName, inputStream);

        ossClent.shutdown();
        String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
        return url;
    }
}
